<template>
  <!-- 左侧 显示便利店信息 -->
  <Row
    type="flex"
    justify="start"
    :gutter="15"
    style="height:calc(100% - 40px); padding-bottom:10px;"
  >
    <i-col :span="7" style="height:100%">
      <div class="charts-border" style="height:100%;">
        <left-layout
          :leftLayoutData="leftLayoutData"
          :axisDataList="axisDataList"
        ></left-layout>
      </div>
    </i-col>
    <!-- 中间 显示总信息，保险柜，卸油口数据-->
    <i-col :span="10" style="height:100%;">
      <center-layout
        :centerLayoutData="centerLayoutData"
        :axisDataList="axisDataList"
        style="height:100%;"
      ></center-layout>
    </i-col>
    <!-- 右侧 显示加油区和卸油口数据-->
    <i-col :span="7" style="height:100%">
      <div class="charts-border" style="height:100%">
        <right-layout></right-layout>
      </div>
    </i-col>
  </Row>
</template>

<script>
import mockData from "@/util/mockData";
import constData from "@/util/constData"; // 保存的常量
import { getIdByValue, sortByAttr } from "@/util/util";
import {
  getLastMonthDate,
  getLastWeekDate,
  formatXAxisData,
  getArrSum
} from "@/util/util";
import { totalScore } from "@/api";
import dayjs from "dayjs";
import LeftLayout from "./leftLayout";
import CenterLayout from "./centerLayout";
import RightLayout from "./rightLayout";

export default {
  name: "analysis",
  components: {
    LeftLayout,
    CenterLayout,
    RightLayout
  },
  props:{
    refresh:{
      type:Boolean,
      default:false
    }
  },
  data() {
    return {
      leftLayoutData:{
        totalScoreData:[],
        typeScoreData:[],
        typeScoreTrandData:{
          serviceData:[],
          safetyData:[],
          manageData:[],
          efficiencyData:[]
        }
      },
      // 中间布局数据
      centerLayoutData: {
        totalScoreData: 0,
        topData: [],
        topStationName: []
      },
      // 横轴数据
      axisDataList: [],
      //mock数据长度 TODO: 真实情况下不需要该属性
      mockDataLength: 0
    };
  },
  watch: {
    $route(val) {
      this.selectedCompany = val.params.companyName;
      this.dateTime = val.params.dateTime;
      this.query();
    },
    refresh(val){
      if(val){
        this.query();
        this.$emit('update:refresh', false);//重置refresh的值
      }
    }
  },
  created() {
    this.dateTime = this.$route.params.dateTime;
    this.selectedCompany = this.$route.params.companyName;
  },
  mounted() {
    this.query();
  },
  methods: {
    // 触发入口
    query(){
      if(this.dateTime === 'today'){
        this.getAllDataByToday();
      }else if(this.dateTime === 'week'){
        this.getAllDataByWeek();
      } else {
        this.getAllDataByMonth();
      }
    },
    // 初始化data
    initData(){
      // this.axisDataList = [];
      this.centerLayoutData.totalScoreData = 0;
      this.centerLayoutData.topData = [];
      this.centerLayoutData.topStationName = [];
      this.leftLayoutData.totalScoreData = [];
      this.leftLayoutData.typeScoreData = [];
      this.leftLayoutData.typeScoreTrandData.serviceData = [];
      this.leftLayoutData.typeScoreTrandData.safetyData = [];
      this.leftLayoutData.typeScoreTrandData.manageData = [];
      this.leftLayoutData.typeScoreTrandData.efficiencyData = [];
    },
    // 获取今日数据
    getAllDataByToday(){
      this.initData();
      let startTime = dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss');
      let endTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
      this.mockDataLength = dayjs(endTime).hour();
      this.axisDataList = ["00:00", "01:00", "02:00", "03:00", "04:00", "05:00", "06:00", "07:00", "08:00", "09:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00", "21:00", "22:00", "23:00"];
      this.getAllData(this.selectedCompany,startTime,endTime);
    },
    // 按周获取数据
    getAllDataByWeek() {
      // 初始化为空
      this.initData();
      let {startTime,endTime} = getLastWeekDate();
      this.axisDataList = formatXAxisData(7,"MM-DD");
      this.mockDataLength = 7;
      this.getAllData(this.selectedCompany,startTime,endTime);
    },
    // 按月获取数据
    getAllDataByMonth() {
      // 初始化为空
      this.initData()
      let {startTime,endTime} = getLastMonthDate();
      let diff = dayjs(endTime).diff(dayjs(startTime),'day');
      this.axisDataList = formatXAxisData(diff,"MM-DD");
      this.mockDataLength = this.axisDataList.length;
      this.getAllData(this.selectedCompany,startTime,endTime)
    },
    // 获取数据
    getAllData(subCompany,startTime,endTime){
      //TODO: constData.subCompanyList=>查询接口返回站点信息
      let subCompanyId = Number(
        getIdByValue(constData.subCompanyList, subCompany)
      );
      //TODO:为了演示效果 前端mock数据 真实情况只需要执行else分支
      if(subCompany==="yulin" || subCompany==="xianyang"){
        let mdata = mockData(this.dateTime,subCompany);
        let len = this.dateTime==='today'?this.mockDataLength+1:this.mockDataLength;
        this.leftLayoutData.totalScoreData = mdata.totalScoreTrandData.slice(0,len);
        this.leftLayoutData.typeScoreTrandData.safetyData = mdata.typeScoreTrandData.safetyData.slice(0,len);
        this.leftLayoutData.typeScoreTrandData.serviceData = mdata.typeScoreTrandData.serviceData.slice(0,len);
        this.leftLayoutData.typeScoreTrandData.manageData = mdata.typeScoreTrandData.manageData.slice(0,len);
        this.leftLayoutData.typeScoreTrandData.efficiencyData = mdata.typeScoreTrandData.efficiencyData.slice(0,len);
        this.leftLayoutData.typeScoreData[0] = (getArrSum(this.leftLayoutData.typeScoreTrandData.safetyData) / len).toFixed(1);
        this.leftLayoutData.typeScoreData[1] = (getArrSum(this.leftLayoutData.typeScoreTrandData.serviceData) / len).toFixed(1);
        this.leftLayoutData.typeScoreData[2] = (getArrSum(this.leftLayoutData.typeScoreTrandData.manageData) / len).toFixed(1);
        this.leftLayoutData.typeScoreData[3] = (getArrSum(this.leftLayoutData.typeScoreTrandData.efficiencyData) / len).toFixed(1);
        this.centerLayoutData.totalScoreData = Number((getArrSum(this.leftLayoutData.totalScoreData) / len).toFixed(1));
        this.centerLayoutData.topData = mdata.top5ScoreData;
        this.centerLayoutData.topStationName = mdata.top5StationName;
      }else{
        this.getTotalScore(subCompanyId, startTime, endTime);
      }
    },
    // 获取总评分
    getTotalScore(company_id, start_time, end_time) {
      let params = {
        company_id,
        start_time,
        end_time
      };
      totalScore(params).then(resdata => {
        // console.log(resdata.data);
        this.initData();
        let group = resdata.data.group;
        let details = resdata.data.details;
        let topCountList = this.getTopCount(resdata.data, true);
        this.centerLayoutData.totalScoreData = resdata.data.general;
        //处理左边布局的数据
        //注意顺序 需和['安全','服务','管理','效率']的顺序一致
        this.leftLayoutData.typeScoreData.push(details["safety"].toFixed(1));
        this.leftLayoutData.typeScoreData.push(details["service"].toFixed(1));
        this.leftLayoutData.typeScoreData.push(details["management"].toFixed(1));
        this.leftLayoutData.typeScoreData.push(details["efficiency"].toFixed(1));

        Object.keys(group).forEach((item,index)=>{
          // if(this.dateTime === 'today'){this.axisDataList.push(group[item].slice(11,));}
          this.leftLayoutData.totalScoreData.push(group[item]["score"].toFixed(1));
          this.leftLayoutData.typeScoreTrandData.safetyData.push(group[item]["details"]["safety"].toFixed(1));
          this.leftLayoutData.typeScoreTrandData.serviceData.push(group[item]["details"]["service"].toFixed(1));
          this.leftLayoutData.typeScoreTrandData.manageData.push(group[item]["details"]["management"].toFixed(1));
          this.leftLayoutData.typeScoreTrandData.efficiencyData.push(group[item]["details"]["efficiency"].toFixed(1));
        });

        //处理中间布局的数据
        let centerTopData = topCountList.map(item => {
          return item.total;
        });
        let centerTopStationName = topCountList.map(item => {
          return item.station;
        });
        this.centerLayoutData.topData =
          centerTopData.length >= 5
            ? centerTopData.slice(0, 5)
            : centerTopData.slice(0);
        this.centerLayoutData.topStationName =
          centerTopStationName.length >= 5
            ? centerTopStationName.slice(0, 5)
            : centerTopStationName.slice(0);
      });
    },
    getStationInfo(obj) {
      //返回站点value
      //TODO: constData.stationList=>今后替换成查询接口获取某公司下的站点信息
      let stationValue = constData.stationList.map((item,index,arr)=>{
        return item.value
      });
      // TODO: constData.stationList2 => 中英文对比，今后替换成查询接口直接有中英文？
      return stationValue.map(item => {
        return {
          station: constData.stationList2[item],
          total: obj[item] ? obj[item]["general"].toFixed(1) : 0
        };
      });
    },
    getTopCount(obj, rev) {
      let stationInfo = this.getStationInfo(obj);
      return sortByAttr(stationInfo, "total", rev);
    }
  }
};
</script>

<style lang="less" scoped></style>
